package filter;

import java.io.ByteArrayInputStream;
import java.io.CharArrayWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.sun.xml.internal.txw2.Document;

import model.Model;
import model.beans.ItemBean;
import model.beans.ShoppingCartBean;

import util.ProjectConstants;

/**
 * Servlet Filter implementation class AdvertiseFilter
 */
@WebFilter(dispatcherTypes =
{ DispatcherType.REQUEST }, urlPatterns =
{ "/shoppingcart" })
public class AdvertiseFilter implements Filter
{
	FilterConfig fConfig = null;
	/**
	 * Default constructor.
	 */
	public AdvertiseFilter()
	{
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy()
	{
		this.fConfig = null;
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException
	{
		ServletContext context = this.fConfig.getServletContext();
		
		System.out.println("start to filter request........");
		// cast ServletRequest to HttpServletRequest
		HttpServletRequest hr = (HttpServletRequest) request;
		// get the request parameter
		String item = hr.getParameter("item");

		// check if the item match the cross selling item
		if (ProjectConstants.TRIGGERITEM.equals(item))
		{
			System.out
					.println("find the trigger item. start to manipulate ..........");

			CharResponseWrapper wrapper = new CharResponseWrapper(
					(HttpServletResponse) response);
			// pass the request along the filter chain
			chain.doFilter(request, wrapper);

			System.out.println("start to filter response.........");

			Model model = (Model) context.getAttribute(ProjectConstants.PARAMMODEL);
			ItemBean itemBean = model.getItemByNumber(ProjectConstants.PROMOTITEM);
			CharArrayWriter caw = new CharArrayWriter();
			StringBuffer buffer = new StringBuffer();
			buffer.append(wrapper.toString());
			String position = "<div class=\"col-full\" id=\"content\">";
			String ads = "<div class=\"col-full\" id=\"content\">  <p class=\"info\"> "
					 + itemBean.getName() +"( "+ ProjectConstants.PROMOTITEM +") is half price! </p>";

			Pattern pattern = Pattern.compile(position);
			Matcher matcher = pattern.matcher(buffer.toString());

			caw.write(matcher.replaceAll(ads));

			response.setContentLength(caw.toString().length());

			PrintWriter out = response.getWriter();
			out.write(caw.toString());
			out.close();
		}
		else
		{
			chain.doFilter(request, response);
		}

	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException
	{
		this.fConfig = fConfig;
	}

}
